//
//  MsgLoginVC.m
//  sensen_ios
//
//  Created by pro on 16/2/1.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "MsgLoginVC.h"

#import "UserOperationView.h"
@interface MsgLoginVC ()

@property (nonatomic, strong) UserOperationView *userView;

@end

@implementation MsgLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"短信验证登录";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createLeftBarButtonItemWithImagename:nil]; // 左侧返回按钮
    
    [self _createViews]; // 创建视图
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    // 设置导航栏颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [self.view endEditing:YES];
}


#pragma mark - 创建视图
- (void)_createViews {
    
    [self _createUserView];
    [self _createButtons];

}
// 创建用户操作视图（登陆，注册等）
- (void)_createUserView {
    
    _userView = [[UserOperationView alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, lineHeight * 2)
                                                  titles:@[@"手机号", @"请输入验证码"]
                                                    type:ZKUserViewMsgLogin];
    [self.scrollView addSubview:_userView];
}


- (void)_createButtons {
    CGFloat x = 20;
    CGFloat y = _userView.bottom + 20;
    CGFloat width = SCREEN_WIDTH - 2 * x;
    CGFloat height = 40;
    
    
    
    // 登录按钮
    UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    loginButton.frame = CGRectMake(x, y, width, height);
    //loginButton.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
    loginButton.backgroundColor = SS_NAVI_ORANGE_COLOR;
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    loginButton.layer.cornerRadius = 2;
    [self.scrollView addSubview:loginButton];
    loginButton.tag = 99;
    loginButton.enabled = YES;
    

}

#pragma mark - 点击事件
- (void)loginAction:(UIButton *)button {
    [_userView getMesLoginInfo:^(NSDictionary *infoDic) {
        
       
        NSString *mobile = infoDic[@"mobile"];
        NSString *code = infoDic[@"code"];
        
        [SVProgressHUD showWithStatus:@"正在登陆"];
        [BoyeHttpClient post:@"BY_User_loginByCode" apiVerson:100 params:@{@"mobile" : mobile, @"code" : code} success:^(AFHTTPRequestOperation *operation, id result) {
            NSLog(@"%@", result);
            
            // 用户信息存储到本地
            NSDictionary *resultDic = result;
            UserModel *user = [[UserModel alloc] initContentWithDic:resultDic];
            [BoyeHttpClient post:@"BY_BbsUserCenter_getUserInfo" apiVerson:100 params:@{@"uid":user.uid} success:^(AFHTTPRequestOperation *operation, id result) {
                if (![result[@"group"] isKindOfClass:[NSNull class]]) {
                    NSDictionary *groupDic = result[@"group"];
                    user.allowdelpost = groupDic[@"allowdelpost"];
                    user.allowstickthread = groupDic[@"allowstickthread"];
                    user.allowdigestthread = groupDic[@"allowdigestthread"];
                    user.fid = groupDic[@"fid"];
                }
                
                
                // 友盟添加别名（根据别名推送）
                [UMessage addAlias:user.uid type:@"sunsun" response:^(id responseObject, NSError *error) {
                    NSLog(@"添加%@", responseObject);
                    NSLog(@"%@", [NSThread currentThread]);
                }];
                
                NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:1];
                
                NSLog(@"设备的唯一标识 = %@", [[CacheFacade sharedCache] get:Device_Token]);
                [dic setObject:[NSString stringWithFormat:@"%@", [[CacheFacade sharedCache] get:Device_Token]] forKey:@"device_token"];
                NSLog(@"uid = %@", user.uid);
                [dic setObject:user.uid forKey:@"uid"];
                [dic setObject:[NSString deviceVersion] forKey:@"version"];
                [dic setObject:@"ios" forKey:@"device_type"];
                
                
                [BoyeHttpClient post:@"BY_Device_bind" apiVerson:100 params:dic success:^(AFHTTPRequestOperation *operation, id result) {
                    [SVProgressHUD showSuccessWithStatus:@"手机号登录成功" withDuration:1];

                    NSLog(@"设备绑定 %@", result);
                    [CommonCache setUserInfo:user];
                    [self dismissViewControllerAnimated:YES completion:nil];  // 返回到跳过来的页面
                    
                    
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    
                    [SVProgressHUD showErrorWithStatus:@"登录名或密码错误，请重新登录" withDuration:1.5];
                    
                }];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [SVProgressHUD showErrorWithStatus:error.domain withDuration:1.5];
            }];
            

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",error.domain] withDuration:1];
        }];

    }];
}


-(void) setLoginInfo:(UserModel * )user{
    
    [CommonCache setUserInfo:user];
    
    // 先删除模态栈
//    [self dismissViewControllerAnimated:YES completion:^{
//        self.tabBarController.selectedIndex = 2;
//        
//    }];
    
    //    self.tabBarController.selectedIndex = 2;
    
    
    
}



#pragma mark - 其他
// 输入框内容改变通知事件
- (void)allTextFieldEndEditing {
    UIButton *loginButton = [self.scrollView viewWithTag:99];
    if ([_userView isAllTextFieldEdited]) {
        loginButton.backgroundColor = SS_NAVI_ORANGE_COLOR;
        loginButton.enabled = YES;
    } else {
        loginButton.backgroundColor = SS_NAVI_ORANGE_COLOR; //[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1];
        loginButton.enabled = YES;
    }
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
